package controller

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-gin-admin/model"
	"github.com/go-gin-admin/util"
	"net/http"
	"time"
)

// 添加角色
func AddRole(c *gin.Context) {
	var roleData model.Role
	if err := c.BindWith(&roleData, binding.JSON); err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("参数解析错误"))
		return
	}
	local := time.Now().Local()
	roleData.CreateTime = local
	roleData.UpdateTime = local
	insertId, err := roleData.AddRole()
	if err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("新建失败"))
		return
	}
	m := make(map[string]interface{})
	m["insertId"] = insertId
	c.JSON(http.StatusOK, new(util.Response).Ok("创建成功", m))
}

// 查询角色
func GetRoleList(c *gin.Context) {
	// 获取参数
	pageSize, _ := util.StringToInt64(c.DefaultQuery("pageSize", "10"))
	pageIndex, _ := util.StringToInt64(c.DefaultQuery("pageIndex", "1"))
	var roleData model.Role
	m, err := roleData.GetRoleList(pageIndex, pageSize)
	if err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("获取失败"))
		return
	}
	c.JSON(http.StatusOK, new(util.Response).Ok("", m))
}

// 查询所有角色
func GetAllRoleList(c *gin.Context) {
	var roleData model.Role
	m, err := roleData.GetAllRoleList()
	if err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("获取失败"))
		return
	}
	c.JSON(http.StatusOK, new(util.Response).Ok("", m))
}

// 更新角色
func UpdateRole(c *gin.Context) {
	var roleData model.Role
	if err := c.BindWith(&roleData, binding.JSON); err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("参数解析错误"))
		return
	}
	roleData.UpdateTime = time.Now().Local()
	if err := roleData.UpdateRole(); err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("更新失败"))
		return
	}
	c.JSON(http.StatusOK, new(util.Response).Ok("", nil))
}

// 删除角色
func DeleteRole(c *gin.Context) {
	var roleData model.Role
	roleId, _ := util.StringToInt64(c.Param("roleId"))
	if err := roleData.DeleteRole(roleId); err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("删除失败"))
		return
	}
	c.JSON(http.StatusOK, new(util.Response).Ok("", nil))
}
